let tilesetFlat = null
let changeLayer = null
let positionArr1 = [[113.123328,27.856434,9.914241394996477],[113.125670,27.854842,10.28501855468462],
[113.124021,27.852680,-0.04107375395608854],[113.121555,27.854246,-0.031079160090569005]];

export function changeBeforeAndAfter(type){
  if (tilesetFlat && changeLayer) {
    tilesetFlat.removePolygon(changeLayer)
    changeLayer = null
  }
  let isShow = true
  if(type === 0){
    positionArr1 = [[113.123328,27.856434,9.914241394996477],[113.125670,27.854842,10.28501855468462], 
                   [113.124021,27.852680,-0.04107375395608854],[113.121555,27.854246,-0.031079160090569005]];
  }else{
    positionArr1 = [[113.124093,27.855373,43.029064444382186],[113.124751,27.855086,43.200481870649135],
                   [113.124437,27.853430,43.50076388525205],[113.123297,27.854262,40.56419850319824]];
    isShow = false
  }

  if (tilesetFlat) {
    changeLayer = tilesetFlat.addPolygon(positionArr1, 33);
  }

  if(shuizhaGlb){
    shuizhaGlb.show = isShow
    doorArr.forEach((item=>{
      item.show = isShow
    }))
  }
  
  if(waterParticleSystem){
    waterParticleSystem.forEach(item => {
      item.show = isShow
    });
  }
  
}

//压平倾斜里面的旧闸
export function flatOldGate(viewer,tile3d){
  tilesetFlat = new Cesium.TilesetFlat(viewer, {
    tileset: tile3d,
    clipOutSide: false
  });

  changeLayer = tilesetFlat.addPolygon(positionArr1, 33);


  var positionArr2 = [[113.136284,27.862812,37.75899430197708],[113.135975,27.863461,37.83021344278416],
      [113.138924,27.864591,37.807216130673915],[113.139196,27.864088,37.77594102226221]];
  tilesetFlat.addPolygon(positionArr2, 33);

  var positionArr3 = [[113.139761,27.865309,40.72286342067794],[113.141741,27.866415,43.497021444536685],
      [113.142104,27.866167,37.986387609671645],[113.145840,27.868932,38.018339766254414],[113.146073,27.869683,38.61711646814679],
      [113.147207,27.870709,41.79359628326042],[113.148844,27.869230,57.91513355956125],[113.147374,27.867418,44.738022136509855],
      [113.140972,27.864350,45.975953985208996]];
  tilesetFlat.addPolygon(positionArr3, 33);


  var positionArr4 = [[113.148132,27.882166,37.97031944760958],[113.147688,27.881795,38.023246722956074],
      [113.146417,27.883047,37.97413370430251],[113.145761,27.883703,37.92944655000521],[113.145989,27.883873,38.01678016038898],
      [113.147024,27.882949,37.9730578041101],[113.147863,27.882371,38.02543097475497]];
  tilesetFlat.addPolygon(positionArr4, 33);


  var positionArr5 = [[113.122282,27.854066,37.03042338807206],[113.122085,27.853546,37.030876837087064],
      [113.120569,27.854175,36.910016508328404],[113.120696,27.854442,36.912894331460535],[113.121710,27.854312,36.96747355918378]];
  tilesetFlat.addPolygon(positionArr5, 33);



  var positionArr6 = [[113.131779,27.860226,37.97840522244355],[113.131094,27.860901,38.12093521415541],
      [113.133275,27.862767,37.80687315319177],[113.133751,27.862897,37.80392846791992],[113.134367,27.861526,37.83658867335839]];
  tilesetFlat.addPolygon(positionArr6, 33);


  var positionArr7 = [[113.130101,27.859420,45.54205525797186],[113.129770,27.859827,41.352678008121885],
      [113.130840,27.860596,37.9317983021119],[113.131241,27.860288,51.425608448329385]];
  tilesetFlat.addPolygon(positionArr7, 33);

}

// //添加水闸模型
// export function addGate(viewer){
//     let modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(113.124426,27.854418,15.174787378835045));
//     let model = viewer.scene.primitives.add(Cesium.Model.fromGltf({
//         url: 'data/model/gate.gltf',
//         modelMatrix: modelMatrix,
//         scale: 0.6,
//         show: true
//     }))
//     model.readyPromise.then(function (model) {
//         let m = model.modelMatrix;
//         let m1 = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(90));
//         Cesium.Matrix4.multiplyByMatrix3(m, m1, m);
//         model.modelMatrix = m;
//     })
// }

let doorArr = [];
let shuizhaGlb = null

//添加水闸模型
export function addGate(viewer){
  let modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(113.12368,27.85456,35.5));
  let m1 = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(-90));
  Cesium.Matrix4.multiplyByMatrix3(modelMatrix, m1, modelMatrix);

  let customShader = new Cesium.CustomShader({
    //不考虑光照模型
    lightingModel: Cesium.LightingModel.UNLIT,
  });

  
  shuizhaGlb = viewer.scene.primitives.add(Cesium.Model.fromGltf({
      customShader,
      url: 'data/水闸/1_lod1.glb',
      modelMatrix: modelMatrix,
      scale: 1.0,
      show: true
  }))



  for(let i = 0; i < 8;i++){
      let model = viewer.scene.primitives.add(Cesium.Model.fromGltf({
          customShader,
          url: 'data/水闸/水闸'+(i+1)+'.glb',
          modelMatrix: modelMatrix,
          scale: 1.0,
          show: true
      }))

      doorArr.push(model);
  }

  changeBeforeAndAfter(1)
}


//开闸门
export function openGate(viewer,indexArr){
  if(doorArr.length > 0){
    let modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(113.12368,27.85456,42.5));
    let m1 = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(-90));
    Cesium.Matrix4.multiplyByMatrix3(modelMatrix, m1, modelMatrix);
  
  
    for(let i = 0 ;i < indexArr.length;i++){
      let index = indexArr[i];
      let doorModel = doorArr[index];
      doorModel.modelMatrix = modelMatrix;
    }
  }
}

//关闸门
export function closeGate(viewer,indexArr){
  if(doorArr.length > 0){
    let modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(113.12368,27.85456,35.5));
    let m1 = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(-90));
    Cesium.Matrix4.multiplyByMatrix3(modelMatrix, m1, modelMatrix);

    for(let i = 0 ;i < indexArr.length;i++){
        let index = indexArr[i];
        let doorModel = doorArr[index];
        doorModel.modelMatrix = modelMatrix;
    }
  }
}


let waterParticleSystem = []
// 添加水闸喷水效果
export function createFlood(viewer) {
    removeWaterSystem(viewer)
    let squirtWaterPoints = [
      {
        x: 113.123205,
        y: 27.854000,
        z: 41
    },
    {

        x: 113.123150,
        y: 27.854000,
        z: 41
    },
    {
        x: 113.123090,
        y: 27.854000,
        z: 41
    },
    {
        x: 113.123020,
        y: 27.854000,
        z: 41
    }
    ]
    squirtWaterPoints.forEach(item => {
        let cartesian = Cesium.Cartesian3.fromDegrees(item.x, item.y, item.z)
        createWaterSystem(viewer,cartesian)
    })
}

// 创建粒子系统（重力）
function createWaterSystem(viewer,position) {
    viewer.clock.shouldAnimate = true;
    viewer.clock.multiplier = 1;
    viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
    viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER;

    const emitterModelMatrix = new Cesium.Matrix4();
    const translation = new Cesium.Cartesian3();
    const rotation = new Cesium.Quaternion();
    let hpr = new Cesium.HeadingPitchRoll(0, Cesium.Math.toRadians(-45), 0);
    const trs = new Cesium.TranslationRotationScale();

    const scene = viewer.scene;
    const particleSystem = scene.primitives.add(
        new Cesium.ParticleSystem({
            image: 'data/img/smoke.png',
            // startColor: Cesium.Color.LIGHTCYAN.withAlpha(1.0),
            startColor: Cesium.Color.WHITE.withAlpha(1.0),
            // startColor: Cesium.Color.fromCssColorString('#f0ffff').withAlpha(1.0),
            endColor: Cesium.Color.WHITE.withAlpha(0.3),
            startScale: 4,
            endScale: 4,
            minimumParticleLife: 2,
            maximumParticleLife: 4,
            minimumSpeed: 15,
            maximumSpeed: 25,
            imageSize: new Cesium.Cartesian2(3, 3),
            emissionRate: 800,
            emitter: new Cesium.CircleEmitter(3.0),
            emitterModelMatrix: computeEmitterModelMatrix(),
            modelMatrix: computeModelMatrix(position),
            updateCallback: applyGravity,
        })
    );

    waterParticleSystem.push(particleSystem);

    // 粒子的位置
    function computeEmitterModelMatrix() {
        // 朝向
        hpr = Cesium.HeadingPitchRoll.fromDegrees(-45, 90, 0, hpr);
        // 原点偏移
        trs.translation = Cesium.Cartesian3.fromElements(-0.5, 1.0, 0.0, translation);
        trs.rotation = Cesium.Quaternion.fromHeadingPitchRoll(hpr, rotation);

        return Cesium.Matrix4.fromTranslationRotationScale(trs, emitterModelMatrix);
    }

    function computeModelMatrix(pos) {
        let modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(pos);
        return modelMatrix;
    }

    const gravityScratch = new Cesium.Cartesian3();

    function applyGravity(p, dt) {
        const position = p.position;
        Cesium.Cartesian3.normalize(position, gravityScratch);

        // 重力
        Cesium.Cartesian3.multiplyByScalar(gravityScratch, -4 * dt, gravityScratch);
        // 运动轨迹
        Cesium.Cartesian3.fromElements(gravityScratch.x - 0.02, (gravityScratch.y - 5) * dt, -5 * dt, gravityScratch);

        p.velocity = Cesium.Cartesian3.add(p.velocity, gravityScratch, p.velocity);
    }

}

// type =true 开启  type = false 关闭
export function changeWaterSystemShow(type,arr) {
  if (waterParticleSystem.length == 0) return;
  arr.forEach(item=>{
    waterParticleSystem[item].show = type
  })
}

// 销毁粒子
export function removeWaterSystem(viewer) {
    const scene = viewer.scene;
    if (waterParticleSystem.length == 0) return;
    waterParticleSystem.forEach(item => {
        scene.primitives.remove(item)
        item.destroy();
    });
    waterParticleSystem = [];
}

//销毁水闸
export function removeGate (viewer) {
  if(shuizhaGlb){
    shuizhaGlb && viewer.scene.primitives.remove(shuizhaGlb)
    doorArr.forEach((item=>{
      viewer.scene.primitives.remove(item)
    }))
  }
}